package com.cn.wanxi.filter;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ResultModel;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter extends HttpFilter {
    /**
     * 去查询doget和dopost的区别？
     * 去查询servlet的生命周期？
     * init   service   destroy
     */
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
// 过滤
        //      0.乱码解决
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String path = req.getServletPath();
        System.out.println(path);
//        /back/user/delete
        if (!path.startsWith("/back/")) {
            chain.doFilter(req, resp);//放行
            return;
        }
        String loginName = (String) req.getSession().getAttribute("loginName");
        boolean isLogin = loginName == null;
        if (!isLogin) {

//        直接可以执行后面的代码（放行）
            chain.doFilter(req, resp);
            return;
        }
        ResultModel resultModel = new ResultModel();
        resultModel.setCode(-1);
        resultModel.setMsg("用户未登录");
        resultModel.setData("/html/login.html");
        resp.getWriter().print(JSONObject.toJSONString(resultModel));

    }

    /**
     * 初始化，项目只加载一次
     */
    @Override
    public void init() {
//  一般情况下这里面会写定时器
    }

    @Override
    public void destroy() {
//  也是执行一次，结束某一个代码
    }
}
